#include<vector>
#include<unordered_map>
#include<queue>
#include<algorithm>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
    
    struct compare {
        constexpr bool operator()(TreeNode* _Left, TreeNode* _Right) const {
            return _Left->val > _Right->val;
        }
    };
public:
    vector<vector<int>> verticalTraversal(TreeNode* root) {
        vector<vector<int>> res;
        if (root == NULL) return res;
        unordered_map<int, priority_queue<TreeNode*,vector<TreeNode*>, compare>> map;
        map[0].push(root);
        int addL = 0;
        while (map.size() > 0) {
            unordered_map<int, priority_queue<TreeNode*, vector<TreeNode*>, compare>> map2;
            for (auto& it : map) {
                while (it.first + addL < 0) {
                    res.emplace(res.begin());
                    ++addL;
                }
                while (it.first + addL >= res.size())
                    res.emplace_back();
                while (!it.second.empty()) {
                    auto& node = it.second.top();
                    res[it.first + addL].push_back(node->val);
                    if (node->left != NULL) 
                        map2[it.first - 1].push(node->left);
                    if (node->right != NULL)
                        map2[it.first + 1].push(node->right);
                    it.second.pop();
                }
            }
            swap(map, map2);
        }
        return res;

    }
};

//class Solution {
//private:
//
//    int dfs(TreeNode* root, int index,int mid, vector<vector<int>>& res) {
//        if (root == NULL) return 0;
//        int addL = 0;
//        if (index < 0) {
//            res.emplace(res.begin());
//            index += 1;
//            mid + 1;
//            addL += 1;
//        }
//        if (index >= res.size())
//            res.emplace_back();
//        auto upper=std::upper_bound(res[index].begin(), res[index].end(), root->val);
//        if (upper == res[index].end())
//            res[index].push_back(root->val);
//        else
//            res[index].insert(upper, root->val);
//        int tmp=dfs(root->left, index-1, mid, res);
//        index += tmp;
//        mid += tmp;
//        addL += tmp;
//        addL+=dfs(root->right, index+1, mid, res);
//        return addL;
//    }
//
//
//public:
//    vector<vector<int>> verticalTraversal(TreeNode* root) {
//        vector<vector<int>> res;
//        dfs(root, -1, -1, res);
//        return res;
//    }
//};